import cryptojs from 'crypto-js';
// 密码DES加密
//随机生成指定数量的16进制key
export const generatekey = (num:number) => {
  let library = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let key = "";
  for (var i = 0; i < num; i++) {
      let randomPoz = Math.floor(Math.random() * library.length);
      key += library.substring(randomPoz, randomPoz + 1);
  }
  return key;
}
// DES(CBC)加密
export const encryptByCBC = function (message:string, key1:string, iv1:string) {
  let key = cryptojs.enc.Utf8.parse(key1);
  let iv = cryptojs.enc.Utf8.parse(iv1);
  let srcs = cryptojs.enc.Utf8.parse(message);
  // 加密模式为CBC，补码方式为PKCS5Padding（也就是PKCS7）
  let encrypted = cryptojs.TripleDES.encrypt(srcs, key, {
          iv: iv,
          mode: cryptojs.mode.CBC,
          padding: cryptojs.pad.Pkcs7
  });
  return cryptojs.enc.Base64.stringify(encrypted.ciphertext);   //返回base64
}

// DES(CBC)解密
export const decryptByCBC = function (message:string, key1:string, iv1:string) {
  let key = cryptojs.enc.Utf8.parse(key1);
  let iv = cryptojs.enc.Utf8.parse(iv1);
  let base64 = cryptojs.enc.Base64.parse(message);
  let src = cryptojs.enc.Base64.stringify(base64);
  // 解密模式为CBC，补码方式为PKCS5Padding（也就是PKCS7）
  let decrypt = cryptojs.TripleDES.decrypt(src, key, {
          iv: iv,
          mode: cryptojs.mode.CBC,
          padding: cryptojs.pad.Pkcs7
  });
  let decryptedStr = decrypt.toString(cryptojs.enc.Utf8);
  return decryptedStr.toString();
}


export default {
  encryptByCBC,
  decryptByCBC,
}